package mvc.struts.annotation.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import mvc.struts.annotation.action.RequestMapping;
import mvc.struts.annotation.entity.Handler;
import mvc.struts.annotation.entity.Request;
import mvc.struts.annotation.util.ArrayUtil;
import mvc.struts.annotation.util.CollectionUtil;

public final class ControllerHelper {

	private	static final Map<Request, Handler>	Action_Map = 
			new HashMap<Request, Handler>();
	
	static {
		
		Set<Class<?>>	controllerClassSet = ClassHelper.getControllerClassSet();
		
		if	(CollectionUtil.isNotEmpty(controllerClassSet))
		{
			for	(Class<?>	controllerClass : controllerClassSet)
			{
				Method[]	methods = controllerClass.getDeclaredMethods();
				
				if	(ArrayUtil.isNotEmpty(methods))
				{
					for	(Method method : methods)
					{
						System.out.println("ControllerHelper - Controller Class Name: " + controllerClass.getName() + 
								",Method Name: " + method.getName());
						
						if	(method.isAnnotationPresent(RequestMapping.class))
						{
							RequestMapping	reqMapping = method.getAnnotation(RequestMapping.class);
											
							//	get method and value
							String	requestMethod = reqMapping.method();
							String	requestPath   = reqMapping.value();
							
							System.out.println("ControllerHelper - requestMethod: " + requestMethod);
							System.out.println("ControllerHelper - requestPath: " + requestPath);
							
							Request	request = new Request(requestMethod.toLowerCase(), requestPath);
							
							Handler	handler = new Handler(controllerClass, method);
						
							Action_Map.put(request, handler);
						}
					}
				}
			}
		}
		else
		{
			System.out.println("controllerClassSet is empty");			
		}
	}
	
	/**
	 * 
	 * @param requestMethod
	 * @param requestPath
	 * @return
	 */
	public static Handler getHandler(String requestMethod, String requestPath)
	{
		Request	request = new Request(requestMethod, requestPath);
		
		return	Action_Map.get(request);
	}
}
